package com.liuwa.common.utils;

import com.liuwa.common.config.PropertiesLoader;
import com.liuwa.common.exception.ServiceException;
import com.liuwa.common.utils.sign.Md5Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Properties;

/**
 * 短信client
 */
public class SmsClient {
	
	private static Logger logger = LoggerFactory.getLogger(SmsClient.class);
	
	/**
	 * 属性文件加载对象
	 */
	private static Properties loader = PropertiesLoader.loadProperties("sms.properties");
	
	private static final String SIGN = loader.getProperty("sms.sign", "");
	private static final String SMS_SERVER_URL = loader.getProperty("sms.url");	   //服务器URL 地址
	private static final String CUST_CODE = loader.getProperty("sms.cust_code");									 //账号
	private static final String PASSWORD = loader.getProperty("sms.password");		 								//密码
	private static final String SP_CODE = loader.getProperty("sms.sp_code");                  //接入码（扩展码）
	/**
	 * 短信发送
	 * @param phone
	 * @param content
	 */
	public static String send(String phone, String content){
		try {
			String result = SmsClient.sendSms(phone, content);
			logger.info("短信发送结果：{}" + result);
			if(!result.toUpperCase().startsWith("SUCCESS")) {
				throw new ServiceException("短信发送失败");
			}
			return result;
		} catch (IOException ex) {
			logger.error(ex.getMessage(), ex);
			throw new ServiceException("短信发送失败");
		}
	}

	public static String sendSms(String mobile, String content) throws IOException {
		return sendSms(mobile, content, SP_CODE, 0);
	}

	public static String sendSms(String mobile, String content, long taskId) throws IOException {
		return sendSms(mobile, content, SP_CODE, taskId);
	}

	public static String sendSms(String mobile, String content, String spCode) throws IOException {
		return sendSms(mobile, content, spCode, 0L);
	}

	public static String sendSms(String mobile, String content, String spCode, long taskId) throws IOException {
		if(SIGN != null && !"".equals(SIGN)) {			
			content = "【" + SIGN + "】" + content;
		}
		content = URLEncoder.encode(content,"utf-8");
        String sign = Md5Utils.hash(content + PASSWORD);
		StringBuilder sb = new StringBuilder();
		sb.append("content=").append(content).append("&destMobiles=").append(mobile)
				.append("&sign=").append(sign).append("&cust_code=").append(CUST_CODE)
				.append("&sp_code=").append(spCode).append("&task_id=").append(taskId);

		String postData = sb.toString();
		logger.info(postData);
		URL url = new URL(SMS_SERVER_URL);
		URLConnection conn = url.openConnection();
		conn.setReadTimeout(1000 * 30);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setAllowUserInteraction(false);

		DataOutputStream server = new DataOutputStream(conn.getOutputStream());

		server.write(postData.getBytes("utf-8"));
		server.close();

		BufferedReader in = new BufferedReader(new InputStreamReader(
				conn.getInputStream(), "utf-8"));
		String result = "", s = "";
		while ((s = in.readLine()) != null)
			result = result + s + "\r\n";
		in.close();
		return result;
	}
}